package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.entity.SysAeration;
import com.ruoyi.system.domain.SysAerationMenu;
import com.ruoyi.system.domain.SysUserAeration;
import com.ruoyi.system.mapper.SysAerationDeptMapper;
import com.ruoyi.system.mapper.SysAerationMapper;
import com.ruoyi.system.mapper.SysAerationMenuMapper;
import com.ruoyi.system.mapper.SysUserAerationMapper;
import com.ruoyi.system.service.ISysAerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;

/**
 * 增氧机 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysAerationServiceImpl implements ISysAerationService
{
    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private SysAerationMapper aerationMapper;

    @Autowired
    private SysUserAerationMapper userAerationMapper;

    @Autowired
    private SysAerationMenuMapper aerationMenuMapper;

    @Autowired
    private SysAerationDeptMapper aerationDeptMapper;

    /**
     * 根据条件分页查询增氧机数据
     *
     * @param sysAeration 增氧机信息
     * @return 增氧机数据集合信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysAeration> selectSysAerationList(SysAeration sysAeration)
    {
        return aerationMapper.selectAerationList(sysAeration);
    }

    /**
     * 根据用户ID查询增氧机
     *
     * @param userId 用户ID
     * @return 增氧机列表
     */
    @Override
    public List<SysAeration> selectSysAerationsByUserId(Long userId)
    {
        List<SysAeration> userAerations = aerationMapper.selectAerationPermissionByUserId(userId);
        List<SysAeration> aerations = selectAerationAll();
        for (SysAeration aeration : aerations)
        {
            for (SysAeration userAeeration : userAerations)
            {
                if (aeration.getAerId().longValue() == userAeeration.getAerId().longValue())
                {
                    aeration.setFlag(true);
                    break;
                }
            }
        }
        return aerations;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectSysAerationPermissionByUserId(Long userId)
    {
        List<SysAeration> perms = aerationMapper.selectAerationPermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysAeration perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getAerKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有增氧机
     *
     * @return 增氧机列表
     */
    @Override
    public List<SysAeration> selectAerationAll()
    {
        return SpringUtils.getAopProxy(this).selectSysAerationList(new SysAeration());
    }

    /**
     * 根据用户ID获取增氧机选择框列表
     *
     * @param userId 用户ID
     * @return 选中增氧机ID列表
     */
    @Override
    public List<Long> selectAerationListByUserId(Long userId)
    {
        return aerationMapper.selectAerationListByUserId(userId);
    }

    /**
     * 通过增氧机ID查询增氧机
     *
     * @param aerId 增氧机ID
     * @return 增氧机对象信息
     */
    @Override
    public SysAeration selectAerationById(Long aerId)
    {
        return aerationMapper.selectAerationById(aerId);
    }

    /**
     * 校验增氧机名称是否唯一
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    public String checkAerationNameUnique(SysAeration sysAeration)
    {
        Long aerId = StringUtils.isNull(sysAeration.getAerId()) ? -1L : sysAeration.getAerId();
        SysAeration info = aerationMapper.checkAerationNameUnique(sysAeration.getAerName());
        if (StringUtils.isNotNull(info) && info.getAerId().longValue() != aerId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验增氧机权限是否唯一
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    public String checkAerationKeyUnique(SysAeration sysAeration)
    {
        Long aerId = StringUtils.isNull(sysAeration.getAerId()) ? -1L : sysAeration.getAerId();
        SysAeration info = aerationMapper.checkAerationKeyUnique(sysAeration.getAerKey());
        if (StringUtils.isNotNull(info) && info.getAerId().longValue() != aerId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验增氧机是否允许操作
     *
     * @param sysAeration 增氧机信息
     */
    @Override
    public void checkAerationAllowed(SysAeration sysAeration)
    {
        if (StringUtils.isNotNull(sysAeration.getAerId()) && sysAeration.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员增氧机");
        }
    }

    /**
     * 校验增氧机是否有数据权限
     *
     * @param aerId 增氧机id
     */
    @Override
    public void checkAerationDataScope(Long aerId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysAeration sysAeration = new SysAeration();
            sysAeration.setAerId(aerId);
            List<SysAeration> sysAerations = SpringUtils.getAopProxy(this).selectSysAerationList(sysAeration);
            if (StringUtils.isEmpty(sysAerations))
            {
                throw new ServiceException("没有权限访问增氧机数据！");
            }
        }
    }

    /**
     * 通过增氧机ID查询增氧机使用数量
     *
     * @param aerId 增氧机ID
     * @return 结果
     */
    @Override
    public int countUserAerationByAerId(Long aerId)
    {
        return userAerationMapper.countUserAerationByAerId(aerId);
    }

    /**
     * 新增保存增氧机信息
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAeration(SysAeration sysAeration)
    {
        // 新增增氧机信息
        aerationMapper.insertAeration(sysAeration);
        return insertAerationMenu(sysAeration);
    }

    /**
     * 修改保存增氧机信息
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAeration(SysAeration sysAeration)
    {
        // 修改增氧机信息
        aerationMapper.updateAeration(sysAeration);
        // 删除增氧机与菜单关联
        aerationMenuMapper.deleteAerationMenuByAerId(sysAeration.getAerId());
        return insertAerationMenu(sysAeration);
    }

    /**
     * 修改增氧机状态
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    public int updateAerationStatus(SysAeration sysAeration)
    {
        return aerationMapper.updateAeration(sysAeration);
    }

    /**
     * 修改数据权限信息
     *
     * @param sysAeration 增氧机信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysAeration sysAeration)
    {
        // 修改增氧机信息
        aerationMapper.updateAeration(sysAeration);
        // 删除增氧机与渔场关联
        roleDeptMapper.deleteRoleDeptByRoleId(sysAeration.getAerId());
        // 新增增氧机和渔场信息（数据权限）
        return insertAerationDept(sysAeration);
    }

    /**
     * 新增增氧机菜单信息
     *
     * @param sysAeration 增氧机对象
     */
    public int insertAerationMenu(SysAeration sysAeration)
    {
        int rows = 1;
        // 新增用户与增氧机管理
        List<SysAerationMenu> list = new ArrayList<SysAerationMenu>();
        if(sysAeration.getMenuIds() != null) {
            for (Long menuId : sysAeration.getMenuIds()) {
                SysAerationMenu rm = new SysAerationMenu();
                rm.setAerId(sysAeration.getAerId());
                rm.setMenuId(menuId);
                list.add(rm);
            }
        }
        if (list.size() > 0)
        {
            rows = aerationMenuMapper.batchAerationMenu(list);
        }
        return rows;
    }

    /**
     * 新增增氧机渔场信息(数据权限)
     *
     * @param sysAeration 增氧机对象
     */
    public int insertAerationDept(SysAeration sysAeration)
    {
        int rows = 1;
        // 新增增氧机与渔场（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : sysAeration.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(sysAeration.getAerId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过增氧机ID删除增氧机
     *
     * @param aerId 增氧机ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAerationById(Long aerId)
    {
        // 删除增氧机与菜单关联
        aerationMenuMapper.deleteAerationMenuByAerId(aerId);
        // 删除增氧机与渔场关联
        aerationDeptMapper.deleteAerationDeptByAerId(aerId);
        return  aerationMapper.deleteAerationById(aerId);
    }

    /**
     * 批量删除增氧机信息
     *
     * @param aerIds 需要删除的增氧机ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAerationByIds(Long[] aerIds)
    {
        for (Long aerId : aerIds)
        {
            checkAerationAllowed(new SysAeration(aerId));
            checkAerationDataScope(aerId);
            SysAeration sysAeration = selectAerationById(aerId);
            if (countUserAerationByAerId(aerId) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", sysAeration.getAerName()));
            }
        }
        // 删除增氧机与菜单关联
        aerationMenuMapper.deleteAerationMenu(aerIds);
        // 删除增氧机与渔场关联
        aerationDeptMapper.deleteAerationDept(aerIds);
        return aerationMapper.deleteAerationByIds(aerIds);
    }

    /**
     * 取消授权用户增氧机
     *
     * @param userAeration 用户和增氧机关联信息
     * @return 结果
     */
    @Override
    public int deleteUserAeration(SysUserAeration userAeration)
    {
        return userAerationMapper.deleteUserAerationInfo(userAeration);
    }

    /**
     * 批量取消授权用户增氧机
     *
     * @param aerId 增氧机ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteDeptAerations(Long aerId, Long[] userIds)
    {
        return userAerationMapper.deleteUserAerationInfos(aerId, userIds);
    }

    /**
     * 批量选择授权用户增氧机
     *
     * @param aerId 增氧机ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertDeptAerations(Long aerId, Long[] userIds)
    {
        // 新增用户与增氧机管理
        List<SysUserAeration> list = new ArrayList<SysUserAeration>();
        for (Long userId : userIds)
        {
            SysUserAeration ur = new SysUserAeration();
            ur.setUserId(userId);
            ur.setAerId(aerId);
            list.add(ur);
        }
        return userAerationMapper.batchUserAeration(list);
    }
}
